package com.smartglass.alfareallive;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothProfile;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.*;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.apache.http.util.EncodingUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.smartglass.alfareallive.R;
import com.ingenic.glass.api.touchboard.GestureDetector;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import cn.ingenic.glasssync.services.SyncModule;

public class AlfaRealLiveMainActivity extends Activity {

    private static final String TAG = "GlassLivePush";
    private static final boolean DEBUG = true;

    private static final int LIVE_SUCCESS = 0;
    private static final int NETWORK_FAIL = 1;
    private static final int SERVER_FAIL = 2;
    private static final int STATE_BLUETOOTH_CONNECTED = 2; //连接上蓝牙设备的状态
    private static final int LVIE_ACTIVITY_REQUEST_CODE = 0;

    private GestureDetector mGestureDetector;

    private Context mContext = null;

    private boolean mVideoLiving = false;

    private AlfaLiveDialog mDialog;
    private LinearLayout llButtomBar;
    private boolean mIsBluetoothConnected = false;  //是否连接上蓝牙设备
    private boolean mIsWIFIConnected = false;       //是否连接WIFI

    LiveParamUtils mLiveParamUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alfa_real_live_main);
        mContext = this;
        mLiveParamUtils = new LiveParamUtils(this);
        initView();
        judgeIsConnectedWIFI();
        //judgeIsConnectedBluetooth();
        mGestureDetector = new GestureDetector(this, new MySimpleGestureDetectorListener());
        Log.d("mIsBluetoothConnected", "" + mIsBluetoothConnected);
        Log.d("mIsWIFIConnected", "" + mIsWIFIConnected);
        if (mIsWIFIConnected) {
            showDialog();
        } else {
            showReturnDialog();
        }
    }


    /**
     * 判断是否连接上WIFI
     */
    private void judgeIsConnectedWIFI() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (mWifi.isConnected()) {
            mIsWIFIConnected = true;
        }
    }


    /**
     * 判断是否连接上蓝牙设备
     */
    private void judgeIsConnectedBluetooth() {
        BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
        int a2dp = -1;
        if (ba != null && ba.isEnabled()) {
            a2dp = ba.getProfileConnectionState(BluetoothProfile.A2DP);   //可操控蓝牙设备，如带播放暂停功能的蓝牙耳机
            if (a2dp == STATE_BLUETOOTH_CONNECTED) {
                mIsBluetoothConnected = true;
            }
        }
    }


    /**
     * 初始化布局
     */
    private void initView() {
        llButtomBar = (LinearLayout) findViewById(R.id.ll_buttom_bar);
    }

    /**
     * 显示对话框
     */
    private void showDialog() {
        mDialog = new AlfaLiveDialog(this, R.style.dialog);
        mDialog.setContentView(R.layout.dialog_alfa_real_live_main);
        mDialog.show();
        mDialog.setAlfaLiveDialogOnTapListener(new AlfaLiveDialog.AlfaLiveDialogOnTapListener() {
            @Override
            public void dialogOnTap() {
                mDialog.dismiss();
                llButtomBar.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 提示退出对话框
     */
    private void showReturnDialog() {
        mDialog = new AlfaLiveDialog(this, R.style.dialog);
        mDialog.setContentView(R.layout.dialog_alfa_real_live_return);
        mDialog.show();
        mDialog.setAlfaLiveDialogOnTapListener(new AlfaLiveDialog.AlfaLiveDialogOnTapListener() {
            @Override
            public void dialogOnTap() {
                mDialog.dismiss();
                System.exit(0);
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return mGestureDetector.onTouchEvent(event);
    }

    class MySimpleGestureDetectorListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSlideLeft(boolean fromPhone) {
            return true;
        }

        @Override
        public boolean onSlideDown(boolean fromPhone) {
            finish();
            mVideoLiving = false;
            return true;
        }

        @Override
        public boolean onTap(boolean fromPhone) {
            llButtomBar.setVisibility(View.INVISIBLE);
            prepareLive();
            return true;
        }
    }

    private void prepareLive() {
        if (!mVideoLiving) {
            Toast.makeText(mContext, "请在手机APP AlfaReal中选择分享平台", Toast.LENGTH_SHORT).show();

            startLive();
        }
    }

    private void startLive() {
        Log.d(TAG, "-------startLive");

        String rtmpPushUrl = null;
        String liveParam = "";

        liveParam = Settings.System.getString(this.getContentResolver(), mLiveParamUtils.LIVE_PARAM);
        if (liveParam == null) { //第一次启动，生成默认参数
            liveParam = mLiveParamUtils.setDefaultLiveParam(this);
        }

        try {
            JSONObject jsonObject = new JSONObject(liveParam);
            rtmpPushUrl = jsonObject.optString("push_url");
            if (rtmpPushUrl == null) {
                Settings.System.putString(this.getContentResolver(), mLiveParamUtils.LIVE_PARAM, "");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        sendLiveUrl(mLiveParamUtils.mPlayUrl);

        if (rtmpPushUrl == null) {
            liveParam = mLiveParamUtils.setDefaultLiveParam(this);
        }

        mLiveParamUtils.readConfig(liveParam);

        Intent cameraLiveIntent = new Intent(mContext, CameraRTMPLive.class);
        cameraLiveIntent.putExtra("liveParam", mLiveParamUtils);
        cameraLiveIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(cameraLiveIntent, LVIE_ACTIVITY_REQUEST_CODE);
        mVideoLiving = true;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case LVIE_ACTIVITY_REQUEST_CODE:
                finish();
                break;
        }
    }


    private void createPushUrl() {
        mhandler.sendEmptyMessage(LIVE_SUCCESS);
    }

    public static final String BROADCAST_SHAREDATA_ACTION = "com.alfareal.sharedata";

    private void sendLiveUrl(String liveUrl) {
        Log.e(TAG, "sendLiveUrl,liveUrl = " + liveUrl);
        Intent intent = new Intent();
        intent.setAction(BROADCAST_SHAREDATA_ACTION);
        intent.putExtra("liveurl", liveUrl);
        sendBroadcast(intent);
    }

    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case LIVE_SUCCESS: {
                    startLive();
                    break;
                }
                case NETWORK_FAIL: {
                    Toast.makeText(AlfaRealLiveMainActivity.this, "网络请求失败，请检查wifi配置", Toast.LENGTH_LONG).show();
                    finish();
                    break;
                }
                case SERVER_FAIL: {
                    Toast.makeText(AlfaRealLiveMainActivity.this, "请求服务器错误，请检查登录账号", Toast.LENGTH_LONG).show();
                    finish();
                    break;
                }
            }
        }
    };


}